﻿//-----------------------------------------------------------------------
// <copyright file="VersionUpgradeApplier.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>15/07/2012</date>
//-----------------------------------------------------------------------
using ConsoleHoster.Common.Utilities;
using System;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleHoster.Model
{
	[Obsolete]
	internal sealed class VersionUpgradeApplier
	{
		private readonly ILogger logger;

		public VersionUpgradeApplier(ILogger argLogger)
		{
			this.logger = new ComponentLogger("VersionUpgradeApplier", argLogger);
		}

		public void ApplyFullVersionUpgrade()
		{
			this.ApplyVersionUpgrade(Int32.MaxValue);
		}

		private void ApplyVersionUpgrade(int argVersionToUpgradeTo)
		{
			this.logger.LogMessage("Checking configuration file version...");
			if (argVersionToUpgradeTo >= 108)
			{
				this.logger.LogMessage("Configuration file version upgrade required.");

				this.UpgradeFromVersion1_07To1_08();
			}
		}

		private void UpgradeFromVersion1_07To1_08()
		{
			this.logger.LogMessage("Updating configuration file version");

			try
			{
				XDocument tmpDocument = XDocument.Load(Constants.ProjectsFilename);
				if (!tmpDocument.Descendants("HosterConfig").Any())
				{
					XElement tmpHosterConfig = new XElement("HosterConfig");
					XElement tmpProjects = tmpDocument.Descendants("Projects").SingleOrDefault();
					if (tmpProjects != null)
					{
						tmpProjects.Remove();
						tmpHosterConfig.Add(tmpProjects);
					}

					tmpDocument.Add(tmpHosterConfig);
					tmpDocument.Save(Constants.ProjectsFilename);
				}
			}
			catch (Exception ex)
			{
				throw new ApplicationException("Unable to upgrade configuration", ex);
			}
		}
	}
}